package api

import (
	"net/http"

	"gitee.com/go-course/go11/vblog/apps/user"
	"gitee.com/go-course/go11/vblog/common"
	"github.com/gin-gonic/gin"
)

func (h *Handler) Login(c *gin.Context) {
	// 初始化一个请求对象
	in := user.NewLoginRequest()
	err := c.BindJSON(in)
	if err != nil {
		common.SendFaild(c, err)
		return
	}

	ins, err := h.svc.Login(c.Request.Context(), in)
	if err != nil {
		common.SendFaild(c, err)
		return
	}

	// 为用户的浏览器设置Cookie
	// domain: localhost,  只把cookie设置在访问local api下面,
	// 127.0.0.1： != localhost
	c.SetCookie(user.AUTH_COOKIE_NAME, ins.AccessToken, 3600*12, "/", "localhost", false, false)

	// 把业务逻辑处理后的结果返回给用户
	c.JSON(http.StatusOK, ins)
}
